﻿/*
* 作者:haojielyb
* 邮箱:haojielyb@qq.com
*/

using Furion.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace Lxb.Model.Service
{
    public class FacedownService : ITransient
    {
        
        private readonly IMemoryCache memoryCache;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private string path = AppDomain.CurrentDomain.BaseDirectory;

        public FacedownService(ISqlSugarClient _db, IMemoryCache memoryCache)
        {
            
            this.memoryCache = memoryCache;
            db = _db;   // 推荐操作
        }

        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="SN"> 设备SN</param>
        /// <param name="uid">用户id</param>
        /// <param name="status">状态</param>
        /// <param name="why">原因</param>
        /// <returns></returns>
        public Boolean Upstate(String SN, int uid, int status = 1, string why = "")
        {
            var sql = "";
            if (status == 1)
            {
                sql = $"update  lxb_face_down_log  set status =1 where SN='{SN}' and  uid= {uid}";
            }
            else
            {
                sql = $"update  lxb_face_down_log  set status =0 ,times=times+1,why='{DateTime.Now.ToString("yyyy/MM/dd HH:mm") + why}'  where SN='{SN}' and  uid= {uid}";
            }

            db.Ado.ExecuteCommand(sql);
            return true;
        }

     
        /// <summary>
        /// 删除已经完成了15天的记录
        /// </summary>
        /// <param name="SN"> 设备SN</param>
        /// <param name="uid">用户id</param>
        /// <param name="status">状态</param>
        /// <param name="why">原因</param>
        /// <returns></returns>
        public Boolean delete(String SN)
        {
            if (memoryCache.Get(SN + "_del") == null)
            {
                memoryCache.Set(SN + "_del", true, new DateTimeOffset(DateTime.Now.AddHours(24)));
                string dt = DateTime.Now.Date.AddDays(-15).ToString("yyyy-MM-dd HH:mm:ss");
                var sql = $"select id from lxb_face_down_log where SN='{SN}' and  status=1 order by id desc limit 100";
                var ids = new List<string>(100);
                using (var reader = db.Ado.GetDataReader(sql))
                {
                   
                    while (reader.Read())
                    {

                        ids.Add(reader[0].ToString());
                    }
                    reader.Close();

                   
                }
                if (ids.Count == 100)
                {
                    var idst = String.Join(",", ids);//;
                    sql = $"delete  from  lxb_face_down_log  where  status =1 and time < '{dt}' and id not in ({idst})";
                    db.Ado.ExecuteCommand(sql);
                }

               
            }
            return true;
        }
    }
}